using admin.application.Services;
using admin.application.Dtos;
using admin.application.Common;
using admin.application.contracts.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace admin.api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly AppAuthService _authService;
    private readonly IJwtTokenService _jwtTokenService;

    public AuthController(AppAuthService authService, IJwtTokenService jwtTokenService)
    {
        _authService = authService;
        _jwtTokenService = jwtTokenService;
    }

    [HttpGet]
    public IActionResult Test()
    {
        return Ok(ResponseResult<object>.Ok(new { 
            message = "Auth API is working!",
            timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            endpoints = new[] { "POST /api/Auth/login", "POST /api/Auth/register" }
        }, "API连接正常"));
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(UserRegisterDto userRegisterDto)
    {
        try
        {
            await _authService.RegisterAsync(userRegisterDto.UserName, userRegisterDto.PassWord);
            return Ok(ResponseResult<object>.Ok(null, "注册成功"));
        }
        catch (Exception ex)
        {
            // 检查是否是用户名已存在的错误
            if (ex.Message.Contains("用户名已存在"))
            {
                return BadRequest(ResponseResult<object>.Fail("用户名已存在，请选择其他用户名", 400));
            }
            return BadRequest(ResponseResult<object>.Fail(ex.Message, 400));
        }
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(UserRegisterDto userRegisterDto)
    {
        try
        {
            var user = await _authService.LoginAsync(userRegisterDto.UserName, userRegisterDto.PassWord);
            if (user == null) 
                return Unauthorized(ResponseResult<object>.Fail("用户名或密码错误", 401));
            
            // 使用 JwtTokenService 生成令牌
            var tokenString = _jwtTokenService.GenerateUserToken(user.Id, user.UserName);

            var loginData = new { 
                userId = user.Id.ToString(), 
                username = user.UserName,
                token = tokenString
            };
            
            return Ok(ResponseResult<object>.Ok(loginData, "登录成功"));
        }
        catch (Exception ex)
        {
            return BadRequest(ResponseResult<object>.Fail(ex.Message, 400));
        }
    }
}